<template>
  <div class="c2c-my-orders">
    <div class="page-header">
      <h2 class="page-title">我的订单</h2>
      <p class="page-subtitle">管理我发布的C2C订单</p>
    </div>
    
    <el-card class="orders-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><List /></el-icon>
          <span>我的订单</span>
          <div style="flex: 1"></div>
          <el-button type="primary" @click="$router.push('/c2c/publish')">
            <el-icon><Plus /></el-icon>
            发布订单
          </el-button>
        </div>
      </template>
      
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px">
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.type" placeholder="全部" clearable>
            <el-option label="买单" value="buy" />
            <el-option label="卖单" value="sell" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable>
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadOrders">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 订单列表 -->
      <el-table :data="orders" style="width: 100%" v-loading="loading">
        <el-table-column prop="orderId" label="订单ID" width="120" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'buy' ? 'success' : 'warning'">
              {{ row.type === 'buy' ? '买单' : '卖单' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="币种" width="100" />
        <el-table-column prop="amount" label="总数量" width="120">
          <template #default="{ row }">
            {{ formatAmount(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click="viewOrderDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.status === 'active'"
              type="danger"
              size="small"
              @click="handleCancelOrder(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadOrders"
        @current-change="loadOrders"
        style="margin-top: 20px"
      />
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="600px">
      <el-descriptions :column="2" border v-if="currentOrder">
        <el-descriptions-item label="订单ID">
          {{ currentOrder.orderId }}
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag :type="currentOrder.type === 'buy' ? 'success' : 'warning'">
            {{ currentOrder.type === 'buy' ? '买单' : '卖单' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="币种">
          {{ currentOrder.currency }}
        </el-descriptions-item>
        <el-descriptions-item label="总数量">
          {{ formatAmount(currentOrder.amount) }}
        </el-descriptions-item>
        <el-descriptions-item label="单价">
          ¥{{ formatAmount(currentOrder.price) }}
        </el-descriptions-item>
        <el-descriptions-item label="总额">
          ¥{{ formatAmount(currentOrder.amount * currentOrder.price) }}
        </el-descriptions-item>
        <el-descriptions-item label="最小金额">
          {{ formatAmount(currentOrder.minAmount || 0) }}
        </el-descriptions-item>
        <el-descriptions-item label="最大金额">
          {{ formatAmount(currentOrder.maxAmount || currentOrder.amount) }}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ currentOrder.paymentMethod }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentOrder.status)">
            {{ getStatusLabel(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ currentOrder.remark || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="发布时间" :span="2">
          {{ formatDate(currentOrder.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { List, Plus } from '@element-plus/icons-vue'
import { c2cApi } from '../api/c2c'

const loading = ref(false)
const orders = ref<any[]>([])
const detailVisible = ref(false)
const currentOrder = ref<any>(null)

const searchForm = reactive({
  type: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

onMounted(() => {
  loadOrders()
})

const loadOrders = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    if (searchForm.type) params.type = searchForm.type
    if (searchForm.status) params.status = searchForm.status
    
    const result = await c2cApi.getMyOrders(params)
    orders.value = result.list || result.orders || []
    pagination.total = result.total || 0
  } catch (error: any) {
    ElMessage.error(error.message || '加载订单失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.type = ''
  searchForm.status = ''
  pagination.page = 1
  loadOrders()
}

const viewOrderDetail = async (order: any) => {
  try {
    const detail = await c2cApi.getOrderDetail(order.orderId)
    currentOrder.value = detail
    detailVisible.value = true
  } catch (error: any) {
    ElMessage.error(error.message || '获取订单详情失败')
  }
}

const handleCancelOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm(
      `确认取消订单 ${order.orderId}？取消后无法恢复。`,
      '确认取消订单',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await c2cApi.cancelOrder(order.orderId)
    ElMessage.success('订单已取消')
    loadOrders()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '取消订单失败')
    }
  }
}

const formatAmount = (value: number) => {
  return value.toFixed(4)
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    active: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return map[status] || ''
}

const getStatusLabel = (status: string) => {
  const map: Record<string, string> = {
    active: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}
</script>

<style scoped>
.c2c-my-orders {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.orders-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}
</style>

